import { Notify, Dialog } from 'vant';
export const Tip = {
    success(message) {
        Notify({
            message,
            duration: 3000,
            background: '#1989fa'
        });
    },
    error(e) {
        const message = (typeof e === 'object' ? e.message : e) || '';
        Notify({
            message,
            duration: 3000,
            background: 'red'
        });
    },
    request({ title, content, call, params }) {
        return new Promise((resolve, reject) => {
            Dialog.confirm({
                title,
                message: content,
            })
                .then(() => {
                    call(params)
                        .then(res => {
                            resolve(res);
                        })
                        .catch(reject);
                })
                .catch(() => {
                    resolve('user:cancel')
                });
        })
    },
    verify(params, promise = true) {
        let fields
        if (Array.isArray(params)) {
            fields = params
        } else {
            fields = params.list
        }
        for (let i = 0; i < fields.length; i++) {
            const { value, rules = [RULES.REQUIRED], error } = fields[i]
            let cache
            const result = rules.every(call => {
                cache = call({ value, error })
                return cache.result
            })
            if (!result) {
                Tip.error(cache.msg)
                return promise ? Promise.reject(cache) : { result: false, data: cache }
            }
        }
        return promise ? Promise.resolve() : { result: true }
    },
};
export function LoadingControl({ call, params, change }) {
  change({
    status: 'loading',
    loading: true
  })
  return call(params)
    .then((res) => {
      change({
        status: 'success',
        loading: false,
        data: res
      })
      return res
    })
    .catch((e) => {
      change({
        status: 'error',
        loading: false
      })
      return Promise.reject(e)
    })
}